# -*- coding:UTF-8 -*-

import logging
from src.sqldata.getdata import SelectData

logging.basicConfig(filename="./log/getsqldata.log", filemode='w',
                    format='%(asctime)s : %(levelname)s : %(message)s',
                    level=logging.DEBUG)


class MysqlData(SelectData):

    def __init__(self):
        SelectData.__init__(self)

    def get_task_data(self, projectname, user, condition='1=1', tasks=None):
        dictstatus = {'wait': '未开始', 'doing': '进行中', 'done': '已完成', 'pause': '已暂停', 'cancel': '已取消', 'closed': '已关闭'}
        dicttype = {'affair': '事务', 'design': '设计', 'devel': '开发', 'test': '测试', 'study': '研究', 'discuss': '讨论',
                    'ui': '界面', 'misc': '其他'}
        countstatus = {"未开始": 0, "进行中": 0, "已完成": 0, "已暂停": 0, "已取消": 0, "已关闭": 0}
        result = []
        try:
            pjids = self.select_data(table='zt_project', showcoloum='id',
                                     condition="name like '%{}%'".format(projectname))
            for p in range(len(pjids)):
                pjid = pjids[p][0]
                # status 状态 assignedTo指派给, type类型, pri优先级, name名称, deadline结束日期
                if tasks == None:
                    tasks = self.select_data(table='zt_task',
                                             showcoloum='status, assignedTo, openedBy,id, type, pri, name, deadline',
                                             condition="{} AND project = '{}' AND (assignedTo = '{}' OR (assignedTo='' and openedBy='{}'))".format(
                                                 condition, pjid, user, user))
                logging.info(tasks)
                # 把数据库返回的数据，转换成对应的中文，返回
                try:
                    if tasks:
                        for tk in tasks:
                            if tk[1] == user or tk[1] == '' and tk[2] == user:
                                task = []
                                task.append(dictstatus[tk[0]])
                                countstatus[dictstatus[tk[0]]] += 1
                                task.append('Task-' + str(tk[3]))
                                task.append(dicttype[tk[4]])
                                task.append(str(tk[5]) + '级')
                                task.append(tk[6])
                                task.append(str(tk[7]).split(" ")[0])
                                result.append(task)
                                logging.info(task)
                except BaseException as e:
                    logging.error(e)
            logging.info(result)
            return countstatus, result
        except BaseException as e:
            logging.error(e)
        # finally:
        #     self.conn.close()

    def get_story_data(self, product, user, plan='', condition='1=1'):
        stages = {'wait': '未开始', 'planned': '已计划', 'projected': '已立项', 'developing': '研发中', 'developed': '研发完毕',
                  'testing': '测试中', 'tested': '测试完毕', 'verified': '已验收', 'released': '已发布', 'closed': '关闭'}
        countstatus = {"未开始": 0, "进行中": 0, "已完成": 0, "已暂停": 0, "已取消": 0, "已关闭": 0}
        try:
            result = []
            pjids = self.select_data(table='zt_product', showcoloum='id',
                                     condition="name like '%{}%'".format(product))
            for p in range(len(pjids)):
                pjid = pjids[p][0]
                # status 所处阶段 assignedTo指派给, openedBy创建者, pri优先级, title名称
                storys = self.select_data(table='zt_story',
                                          showcoloum='stage, assignedTo, openedBy,id, pri, title, lastEditedDate',
                                          condition="{} AND product = '{}' AND plan = '{}' AND (assignedTo='{}' OR (assignedTo= '' AND openedBy ='{}'))".format(
                                              condition, pjid, plan, user, user))
                logging.info(storys)
                if storys:
                    for st in storys:
                        if st[1] == user or st[1] == '' and st[2] == user:
                            story = []
                            if stages[st[0]] in ['未开始']:
                                story.append('未开始')
                                countstatus['未开始'] += 1
                            elif stages[st[0]] in ['已计划', '已立项', '研发中', '研发完毕', '测试中']:
                                story.append('进行中')
                                countstatus['进行中'] += 1
                            elif stages[st[0]] in ['测试完毕', '已验收', '已发布']:
                                story.append('已完成')
                                countstatus['已完成'] += 1
                            elif stages[st[0]] in ['关闭']:
                                story.append('已关闭')
                                countstatus['已关闭'] += 1
                            story.append('Story-' + str(st[3]))
                            story.append('  ')
                            story.append(str(st[4]) + '级')
                            story.append(st[5])
                            story.append(str(st[6]).split(" ")[0])
                            result.append(story)
            logging.info(result)
            return countstatus, result
        except BaseException as e:
            logging.error(e)
        # finally:
        #     self.conn.close()

    def get_bug_data(self, product, user, condition='1=1'):
        dictstatus = {'active': '进行中', 'resolved': '已完成', 'close': '已关闭'}
        dicttype = {'codeerror': '代码错误', 'interface': '界面优化', 'config': '配置相关', 'install': '安装部署', 'security': '安全相关',
                    'performance': '性能问题', 'standard': '标准规范', 'designdefect': '设计缺陷'}
        countstatus = {"未开始": 0, "进行中": 0, "已完成": 0, "已暂停": 0, "已取消": 0, "已关闭": 0}
        result = []
        try:
            pjids = self.select_data(table='zt_product', showcoloum='id',
                                     condition="name like '%{}%'".format(product))
            for p in range(len(pjids)):
                pjid = pjids[p][0]
                # status 状态 assignedTo指派给, type类型, pri优先级, name名称, deadline结束日期

                bugs = self.select_data(table='zt_bug',
                                        showcoloum='status,assignedTo, openedBy,id,type,severity,pri,title,deadline',
                                        condition="{} AND product = '{}' AND (assignedTo = '{}' OR (assignedTo ='' AND openedBy ='{}'))".format(
                                            condition, pjid, user, user))
                logging.info(bugs)
                # 把数据库返回的数据，转换成对应的中文，返回
                try:
                    if bugs:
                        for bg in bugs:
                            if bg[1] == user or bg[1] == '' and bg[2] == user:
                                bug = []
                                bug.append(dictstatus[bg[0]])
                                countstatus[dictstatus[bg[0]]] += 1
                                bug.append('Bug-' + str(bg[3]))
                                bug.append(dicttype[bg[4]] if dicttype[bg[4]] else '其他')
                                bug.append('Y' + str(bg[5]) + 'U' + str(bg[6]) + '级')
                                bug.append(bg[7])
                                bug.append(str(bg[8]).split(" ")[0])
                                result.append(bug)
                                logging.info(bug)
                except BaseException as e:
                    logging.error(e)
            logging.info(result)
            return countstatus, result
        except BaseException as e:
            logging.error(e)

    def get_dayport_data(self, user, enday):
        from src.sqldata.sqlitedata import SqliteData
        sqd = SqliteData()
        try:
            daydata = self.select_history_action(user, enday)
            if daydata:
                sqd.sqcor.execute("delete from dayport_data;")
                sqd.sqconn.commit()
                for dd in daydata:
                    data = []
                    day = str(dd[0]).split(" ")[0]
                    data.append(day)
                    data = data + list(dd[1:])
                    sqd.insert_data(table='dayport_data', value=data)
                sqd.sqcor.execute("select DISTINCT(daytime) from dayport_data;")
                distday = sqd.sqcor.fetchall()
                tabledata = []
                for did in distday:
                    didvalue = sqd.select_data(table='dayport_data', showcols='type, dataid,newest_v',
                                               condition="daytime = '{}'".format(did[0]))
                    done, closed, cancel = [], [], []
                    for dv in didvalue:
                        if dv[-1] == 'done':
                            done.append(dv[0].title() + '-' + str(dv[1]))
                        elif dv[-1] == 'closed':
                            closed.append(dv[0].title() + '-' + str(dv[1]))
                        elif dv[-1] == 'cancel':
                            cancel.append(dv[0].title() + '-' + str(dv[1]))
                    count = "共完成 {} 个，关闭 {} 个，取消 {} 个".format(len(done), len(closed), len(cancel))
                    result = [did[0], [done, closed, cancel], count]
                    tabledata.append(result)
                logging.info(tabledata)
                return tabledata
            else:
                return False
        except BaseException as e:
            logging.error(e)
        finally:
            sqd.sqcor.close()

    def sqlite_dayport_data(self, condition):
        from src.sqldata.sqlitedata import SqliteData
        sqd = SqliteData()
        try:
            selvalue = sqd.select_data(table='dayport_data', showcols='daytime,type,dataid,newest_v',
                                       condition=condition)
            return selvalue
        except BaseException as e:
            logging.error(e)
        finally:
            sqd.sqcor.close()

    def export_sqlite_data(self, condition='1=1'):
        epdata = self.sqlite_dayport_data(condition)

    def count_data(self,table,condition):
        from src.sqldata.sqlitedata import SqliteData
        sqd = SqliteData()
        result = sqd.count_data(table=table, condition=condition)
        return result
